﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight.Ioc;
using Tisbi.LawFirm.BL;
using Tisbi.LawFirm.BL.Services;
using Tisbi.LawFirm.DAL.Models;
using Tisbi.LawFirm.UI.Views.Controls.Forms;

namespace Tisbi.LawFirm.UI.ViewModel
{
    public class AppealsViewModel : BaseViewModel<Appeals, IAppealsServiceAgent>
    {
        public int LawsuitId { get; set; }
        
        protected override void LoadModelBySearch()
        {
            IsBusy = true;

            ModelServiceAgent.GetItemByLawsuits
                (
                    LawsuitId,
                    (list, exception) =>
                        ModelLoadedByWhere(list, exception, item => item.Title.Contains(SearchCriteria))
                );
        }

        protected override void ShowEditDialog()
        {
            if (SelectedModelItem == null)
            {
                return;
            }

            var model = new AppealsCRUDViewModel(SelectedModelItem);
            ShowEditDialog<AppealsCRUDForm>(model, "Карточка изменения апелляций");
        }

        protected override void ShowCreatedDialog()
        {
            List<AppealsType> allRoles = Enum.GetValues(typeof(AppealsType)).Cast<AppealsType>().ToList();
            List<AppealsType> usedRoles = new List<AppealsType>(allRoles.Count);
            usedRoles.AddRange(Model.Select(appealse => appealse.AppealsType));

            var appealsTypes = allRoles.Except(usedRoles).ToList();
            if (!appealsTypes.Any())
            {
                Notifyer.Notify("У иска может быть максимум по одной апеляции на один тип, удалите или измените имеющиеся.");
                return;
            }

            var newItem = new Appeals();
            var detailModel = new AppealsCRUDViewModel(newItem)
            {
                SelectedAppealsType = appealsTypes.First(),
                AppealsTypes = appealsTypes
            };

            ShowCreatedDialog<AppealsCRUDForm>(detailModel, "Карточка создания новой апелляции");
        }

        protected override void LoadModel()
        {
            // Flip busy flag
            IsBusy = true;

            // Load items
            ModelServiceAgent.GetItemByLawsuits
                (
                    LawsuitId,
                    ModelLoaded
                );
        }

        protected override void Add(Appeals newItem)
        {
            if (newItem != null)
            {
                var lawsuitsViewModel = SimpleIoc.Default.GetInstance<LawsuitsViewModel>();
                var detailModel = lawsuitsViewModel.DetailModel;

                Lawsuits lawsuits = lawsuitsViewModel.SelectedModelItem;
                if (detailModel != null && (lawsuits == null || detailModel.Model.Id == 0))
                {
                    if (detailModel.Model.Appeals == null)
                    {
                        detailModel.Model.Appeals = new List<Appeals>();
                    }
                    detailModel.Model.Appeals.Add(newItem);

                    Model = new ObservableCollection<Appeals>(detailModel.Model.Appeals);
                    
                    if (PopUpDialog != null)
                    {
                        PopUpDialog.Close();
                    }
                    return;
                }

                ModelServiceAgent.AddItem(newItem, ItemsSaved);

                if (lawsuits.Appeals == null)
                {
                    lawsuits.Appeals = new List<Appeals>();
                }
                lawsuits.Appeals.Add(newItem);

                LawsuitsServiceAgent.Edit(lawsuits, delegate(Exception error)
                {
                    if (error != null)
                    {
                        Notifyer.NotifyError("Unable to save items", error);
                    }
                });

                LoadModel();
            }

            if (PopUpDialog != null)
            {
                PopUpDialog.Close();
            }
        }

        public void ReloadModel(int lawsuitId)
        {
            LawsuitId = lawsuitId;
            LoadModel();
        }
    }
}
